package com.pucong.gitee.database.backup.business.sys.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pucong.gitee.database.backup.business.sys.cover.SysUserBeanConvert;
import com.pucong.gitee.database.backup.business.sys.mapper.SysRoleUserMapper;
import com.pucong.gitee.database.backup.business.sys.mapper.SysUserInfoMapper;
import com.pucong.gitee.database.backup.common.entity.sys.SysRoleUser;
import com.pucong.gitee.database.backup.common.entity.sys.SysUserInfo;
import com.pucong.gitee.database.backup.common.entity.sys.UserJwt;
import com.pucong.gitee.database.backup.common.entity.sys.dto.SysUserInfoSaveDto;
import com.pucong.gitee.database.backup.common.entity.sys.vo.SysUserInfoVo;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.utils.AESEncryptUtil;
import com.pucong.gitee.database.backup.utils.SystemConstant;
import com.pucong.gitee.database.backup.utils.UUID;
import com.pucong.gitee.database.backup.utils.UserRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户基础信息 service实现类
 *
 * @author pucong
 * @company gitee.com/pucong
 * @create 2020-12-01
 */
@Service
@Slf4j
public class SysUserInfoServiceImpl implements SysUserInfoService {

    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private SysUserBeanConvert sysUserBeanConvert;

    @Override
    public IPage getRmUserInfoListByPage(int pageNum, int pageSize, SysUserInfo sysUserInfo){
        UserJwt loginUser = UserRequest.getLoginUser();
        List<String> ids = selectChildrenUserId();
        Page<SysUserInfo> page = new Page<>(pageNum, pageSize);
        IPage<SysUserInfo> rmUserInfoIPage = sysUserInfoMapper.getRmUserInfoListByPage(page, sysUserInfo,loginUser.getUuid(),ids);
        return rmUserInfoIPage;
    }

    @Override
    public SysUserInfoVo getRmUserInfoById(String id){
        SysUserInfo sysUserInfo = sysUserInfoMapper.selectById(id);
        SysUserInfoVo sysUserInfoVo = sysUserBeanConvert.do2vo(sysUserInfo);
        LambdaQueryWrapper<SysRoleUser> selectRole = new LambdaQueryWrapper<>();
        selectRole.eq(SysRoleUser::getUserId, id);
        List<SysRoleUser> sysRoleUsers = sysRoleUserMapper.selectList(selectRole);
        List<String> collect = sysRoleUsers.stream().map(SysRoleUser::getRoleId).collect(Collectors.toList());
        sysUserInfoVo.setRoleIds(collect);
        return sysUserInfoVo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int insertRmUserInfo(SysUserInfoSaveDto dto){
        UserJwt loginUser = UserRequest.getLoginUser();
        // 校验账号是否重复
        LambdaQueryWrapper<SysUserInfo> selectUsername = new LambdaQueryWrapper<>();
        selectUsername.eq(SysUserInfo::getLoginName, dto.getLoginName());
        List<SysUserInfo> sysUserInfos = sysUserInfoMapper.selectList(selectUsername);
        if(sysUserInfos.size() > 0){
            throw new BusinessException("账号重复");
        }
        SysUserInfo sysUserInfo = new SysUserInfo();
        String uuid = UUID.uuid();
        sysUserInfo.setLoginName(dto.getLoginName());
        sysUserInfo.setUserName(dto.getUserName());
        sysUserInfo.setStatus(dto.getStatus());
        sysUserInfo.setUuid(uuid);
        sysUserInfo.setCreateBy(loginUser.getUuid());
        sysUserInfo.setCreateTime(new Date());
        // 加密密码
        sysUserInfo.setPassword(AESEncryptUtil.encrypt(SystemConstant.SYS_DEFAULT_PWS));
        // 设置路径
        SysUserInfo sysUserInfo1 = sysUserInfoMapper.selectById(loginUser.getUuid());
        sysUserInfo.setCreateByPath(sysUserInfo1.getCreateByPath() + "," + uuid);
        sysUserInfoMapper.insert(sysUserInfo);
        // 设置角色
        // 删除所有
        LambdaQueryWrapper<SysRoleUser> deleteRoleUser = new LambdaQueryWrapper<>();
        deleteRoleUser.eq(SysRoleUser::getUserId, sysUserInfo.getUuid());
        sysRoleUserMapper.delete(deleteRoleUser);
        List<String> roleIds = dto.getRoleIds();
        if(roleIds.size() > 0){
            for (String roleId : roleIds) {
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setUuid(UUID.uuid());
                sysRoleUser.setUserId(sysUserInfo.getUuid());
                sysRoleUser.setRoleId(roleId);
                sysRoleUser.setCreateBy(loginUser.getUuid());
                sysRoleUser.setCreateTime(new Date());
                sysRoleUserMapper.insert(sysRoleUser);
            }
        }
        return 1;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int updateRmUserInfoById(String id, SysUserInfoSaveDto dto){
        UserJwt loginUser = UserRequest.getLoginUser();
        SysUserInfo sysUserInfoUpdate = new SysUserInfo();
        sysUserInfoUpdate.setUuid(id);
        sysUserInfoUpdate.setLoginName(dto.getLoginName());
        sysUserInfoUpdate.setUserName(dto.getUserName());
        sysUserInfoUpdate.setStatus(dto.getStatus());
         sysUserInfoMapper.updateById(sysUserInfoUpdate);
        // 设置角色
        // 删除所有
        LambdaQueryWrapper<SysRoleUser> deleteRoleUser = new LambdaQueryWrapper<>();
        deleteRoleUser.eq(SysRoleUser::getUserId, id);
        sysRoleUserMapper.delete(deleteRoleUser);
        List<String> roleIds = dto.getRoleIds();
        if(roleIds.size() > 0){
            for (String roleId : roleIds) {
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setUuid(UUID.uuid());
                sysRoleUser.setUserId(id);
                sysRoleUser.setRoleId(roleId);
                sysRoleUser.setCreateBy(loginUser.getUuid());
                sysRoleUser.setCreateTime(new Date());
                sysRoleUserMapper.insert(sysRoleUser);
            }
        }
        return 1;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int deleteRmUserInfoById(String id){
        int i = sysUserInfoMapper.deleteById(id);
        // 删除用户关联角色
        LambdaQueryWrapper<SysRoleUser> params = new LambdaQueryWrapper<>();
        params.eq(SysRoleUser::getUserId, id);
        sysRoleUserMapper.delete(params);
        return i;
    }

    @Override
    public int restPwd(String id) {
        SysUserInfo sysUserInfoUpdate = new SysUserInfo();
        sysUserInfoUpdate.setUuid(id);
        sysUserInfoUpdate.setPassword(AESEncryptUtil.encrypt(SystemConstant.SYS_DEFAULT_PWS));
        return sysUserInfoMapper.updateById(sysUserInfoUpdate);
    }

    @Override
    public List<String> selectChildrenUserId() {
        UserJwt loginUser = UserRequest.getLoginUser();
        if(!"superadmin".equals(loginUser.getLoginName())){
            List<String> userId = sysUserInfoMapper.selectChildrenUserId(loginUser.getUuid());
            return userId;
        }else{
            return null;
        }
    }
}
